package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class Mytask {
    @Autowired
    private OrderMapper orderMapper;
    // 订单处于待支付15分钟后自动超时 每一分钟检查一次
    @Scheduled(cron = "0/60 * * * * ? ")
    public void orderOutTime(){
        log.info("订单超时取消处理:{}",LocalDateTime.now());
        LocalDateTime orderTime = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = orderMapper.getInfoByStatusAndOrderTime(Orders.PENDING_PAYMENT,orderTime);

        // 修改订单的状态、取消原因、取消时间
        for (Orders orders : ordersList) {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            orders.setCancelReason("订单超时取消");
            orderMapper.update(orders);
        }

    }
    // 订单处于带派送状态时在自动完成
    @Scheduled(cron = "0 0 1 * * ?")
    public void orderDelivery(){
        log.info("订单派送定时处理:{}",LocalDateTime.now());
        // 状态为派送中，时间为晚上十二点之前的所有订单
        LocalDateTime orderTime = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.getInfoByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, orderTime);

        for (Orders orders : ordersList) {
            orders.setStatus(Orders.COMPLETED);
            orderMapper.update(orders);
        }
    }
}
